package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@RequiredArgsConstructor
public class AdminServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    private final AdUserMapper adminMapper;

    /**
     * 根据用户名和密码 是否正确登录
     *
     * @param adUserDto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        log.info("入参{}",adUserDto);
        // 1、检查参数
        if (adUserDto == null || adUserDto.getName() == null || adUserDto.getPassword() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 2、查询用户
        AdUser adUser = adminMapper.selectByName(adUserDto.getName());
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 3、比对密码
        String salt = adUser.getSalt();
        String password = adUserDto.getPassword();
        password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        log.info("密码对比{}",password);
        if(password.equals(adUser.getPassword())){
            // 比对正确
            adUser.setSalt("");
            adUser.setPassword("");
            Map<String,Object> map=new HashMap<>();
            map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
            map.put("user",adUser);
            return ResponseResult.okResult(map);
        }else{
            // 比对错误
            log.info("密码错误{}",adUserDto.getPassword());
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
    }
}
